package com.ruoyi.common.utils.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ws.schild.jave.*;

import java.io.File;
import java.net.URL;

/**
 * @Author liumaotong
 * @Description 视频压缩工具
 * @Date 2024/4/2
 */
public class VedioUtils {

    private static final Logger log = LoggerFactory.getLogger(VedioUtils.class);

    private static final Integer TARGETBITRATE = 5_600_000;

    public static void compre(File source , File target , Integer rate) throws EncoderException {
        Integer targetRate = TARGETBITRATE/rate;
        //判断原视频比特率低于阈值时 不压缩
        MultimediaObject media = new MultimediaObject(source);
        MultimediaInfo info = media.getInfo();
        VideoInfo sourceVideo = info.getVideo();
        Integer bitRate = sourceVideo.getBitRate();
        if(bitRate <= targetRate){
            log.info("文件比特率：" + bitRate + ",低于预设值,不压缩");
            return;
        }
        Integer width = (int)(sourceVideo.getSize().getWidth() * (float)0.8);
        Integer height = (int)(sourceVideo.getSize().getHeight() * (float)0.8);
        log.info("============= 压缩文件Start =============");
        long start = System.currentTimeMillis();
        // 音频编码属性配置
        AudioAttributes audio= new AudioAttributes();
        audio.setCodec("libmp3lame");
        // 设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 56000 = 56kb)
        audio.setBitRate(new Integer(56_000));
        // 设置重新编码的音频流中使用的声道数（1 =单声道，2 = 双声道（立体声））
        audio.setChannels(2);
        // 采样率越高声音的还原度越好，文件越大
        audio.setSamplingRate(new Integer(44100));

        // 视频编码属性配置
        VideoAttributes video=new VideoAttributes();
        // 设置编码
        video.setCodec("mpeg4");
        //设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 5600000 = 5600kb)
        video.setBitRate(targetRate);
        // 设置视频帧率（帧率越低，视频会出现断层，越高让人感觉越连续）,这里 除1000是为了单位转换
        video.setFrameRate(new Integer(24));

        VideoSize size = new VideoSize(width,height);
        video.setSize(size);

        // 编码设置
        EncodingAttributes attr=new EncodingAttributes();
        attr.setFormat("mp4");
        attr.setAudioAttributes(audio);
        attr.setVideoAttributes(video);

        // 设置值编码
        Encoder ec = new Encoder();
        ec.encode(new MultimediaObject(source), target, attr);

        log.info("============= 压缩文件end =============");
        long end = System.currentTimeMillis();
        log.info("压缩前大小： "+source.length() + " 压缩后大小：" + target.length());

        log.info("压缩耗时： " + (end -start));
    }

}
